package com.kylin.common.security.service;

import com.kylin.common.security.exception.AuthErrorMessage;
import com.kylin.common.security.service.handler.LoginHandler;
import com.kylin.common.security.service.handler.LoginHandlerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取用户信息
 * @author wuhao
 * @version 1.0 - 2022/8/17
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    HttpServletRequest request;

    @Autowired
    LoginHandlerFactory loginHandlerFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 获取授权登录处理器
        String grantType = request.getParameter("grant_type");
        LoginHandler loginHandler;
        try {
            loginHandler = loginHandlerFactory.getLoginHandler(grantType);
        }catch (Exception e) {
            // 未找到对应的授权模式
            throw new InternalAuthenticationServiceException(AuthErrorMessage.NOT_FOUND_GRANT_TYPE.getMessage());
        }

        // redis缓存方式

        // 具体的登录方法交给不同的登录处理器处理
        return loginHandler.handle(request);
    }
}
